<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <style>
        canvas {
            border: 1px solid #000;
        }
    </style>
</head>

<body>
    <canvas id="snakeCanvas" width="1400" height="600"></canvas>

    <script>
        const canvas = document.getElementById("snakeCanvas");
        const ctx = canvas.getContext("2d");

        const rec_x = 100;
        const rec_y = 20;
        let snake_head = { x: 10, y: 10 };
        let direction = "right";

        function draw() {
            // 清空画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            // 绘制蛇
            ctx.fillStyle = "#0000FF";
            /* 第一,第二个参数 表示起点坐标
                    第三个参数 width
                    第四个参数 height
                */
            ctx.fillRect(snake_head.x, snake_head.y, rec_x, rec_y);
            // 移动蛇
            switch (direction) {
                case "up":
                    snake_head.y -= 5;
                    break;
                case "down":
                    snake_head.y += 5;
                    break;
                case "left":
                    snake_head.x -= 5;
                    break;
                case "right":
                    snake_head.x += 5;
                    break;
            }

            
        }

        function changeDirection(event) {
            switch (event.key) {
                case "ArrowUp":
                    direction = "up";
                    break;
                case "ArrowDown":
                    direction = "down";
                    break;
                case "ArrowLeft":
                    direction = "left";
                    break;
                case "ArrowRight":
                    direction = "right";
                    break;
            }
        }

        function gameLoop() {
            draw();
            requestAnimationFrame(gameLoop);
        }

        // 监听键盘事件
        window.addEventListener("keydown", changeDirection);

        // 启动游戏循环
        gameLoop();
    </script>
</body>

</html>